//
//  OtherAPI.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/4/8.
//

import Foundation
import Moya

// RequestAPI就是一个遵循TargetType协议的枚举
enum OtherAPI {
    // 正式
    
    case translation(from: String, to: String, text: String)
    
    /// 图片识别 翻译
    case pictureOCR(image: Data, from: String, to: String, isTranslation: Bool)
    
    /// 语音文件翻译
    case fileTrans(fileURL: String, language: String)
    
    /// 语音文件翻译查询结果
    case fileTransResult(taskId: String, language: String)
    
    // 占位
    case placeholderApi
}

extension OtherAPI: TargetType {
    // 请求地址
    var baseURL: URL {
        
        switch self {
        case .translation:
            return URL(string: "https://1an04la087286.vicp.fun")!
            
        case .pictureOCR:
            return URL(string: "https://1an04la087286.vicp.fun")!
            
        case .fileTrans(let fileURL, let language):
            switch language {
            case "zh":
                return URL(string: "https://1an04la087286.vicp.fun")!
            default:
                return URL(string: "https://1an04la087286.vicp.fun")!
            }
        
        case .fileTransResult(let taskId, let language):
            switch language {
            case "zh":
                return URL(string: "https://1an04la087286.vicp.fun")!
            default:
                return URL(string: "https://1an04la087286.vicp.fun")!
            }
            
        case .placeholderApi: break
            
        }
        return URL(string: SystemEnvManager.shared.phpUrl)!
    }
    
    // 请求API
    var path: String {
        switch self {
        case .translation: return "/wsttrans/api/v1/textTranslation"
        case .pictureOCR: return "/wsttrans/api/v1/ocr?apikey=3bc9127c78fe827bb726108bb3559ba4"
            
        case .fileTrans(let fileURL, let language):
            switch language {
            case "zh":
                return "/wsttrans/api/v1/zh/filetrans"
            default:
                return "/wsttrans/api/v1/ru/filetrans"
            }
            
        case .fileTransResult(let taskId, let language):
            switch language {
            case "zh":
                return "/wsttrans/api/v1/zh/filetrans"
            default:
                return "/wsttrans/api/v1/ru/filetrans"
            }
            
        default:
            fatalError("Request path is null")
        }
    }
    
    // 请求方式: post/get
    var method: Moya.Method {
        switch self {
        case .placeholderApi, .fileTransResult:
            return .get
            
        default: // 默认post请求
            return .post
        }
    }
    
    // 请求任务
    var task: Moya.Task {
        // 公共参数
        var params: [String: Any] = [:]
        
        // 根据不同的接口传入不同的参数
        switch self {
            
        case .translation(let from, let to, let text):
            params["from"] = from
            params["to"] = to
            params["src_text"] = text
            
        case .pictureOCR(_, let from, let to, let isTranslation):
            params["apikey"] = KeyCenter.NiuTrans.apiKey
            params["source_language"] = from
            params["target_language"] = to
            params["is_translate"] = isTranslation
            
            
        default:
            break
        }
        
        // 设置请求类型, 比如没有参数的请求、有参数的请求、上传文件、下载文件
        switch self {
        case .placeholderApi:
            // 没有请求参数的请求。
            return .requestPlain
            
        case .pictureOCR(let image, let from, let to, let isTranslation):
            // 必须得传文件名,否则报错
            return .uploadMultipart([
                MultipartFormData(
                    provider: .data(image),
                    name: "file",
                    fileName: "\(Date.sg.timestamp()).jpeg",
                    mimeType: "image/jpeg"
                ),
                MultipartFormData(provider: .data(from.data(using: .utf8)!), name: "source_language"),
                MultipartFormData(provider: .data(to.data(using: .utf8)!), name: "target_language"),
                MultipartFormData(provider: .data("\(isTranslation)".data(using: .utf8)!), name: "is_translate")
            ])
            
        case .translation:
            // get 请求报错，说 不支持 get，
            // post 请求参数放在 body 中，后台插入不了数据，放在 url 中，接口就能调通
            return .requestCompositeParameters(bodyParameters: params, bodyEncoding: JSONEncoding.default, urlParameters: ["apikey": KeyCenter.NiuTrans.apiKey])
            
        case .fileTrans(let fileURL, let language):
            params["apikey"] = KeyCenter.NiuTrans.apiKey
            params["token"] = "default"
            params["file_link"] = fileURL
            return .requestCompositeParameters(bodyParameters: params, bodyEncoding: JSONEncoding.default, urlParameters: ["apikey": KeyCenter.NiuTrans.apiKey])
        case .fileTransResult(let taskId, let language):
            params["apikey"] = KeyCenter.NiuTrans.apiKey
            params["task_id"] = taskId
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
            
            //        case .imScore, .imCheck, .systemMsg:
            //            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
            //
            //        default:
            //            // 默认有请求参数
            //            if method == .get {
            //                // 在发起GET请求时，确保使用 URLEncoding.default 编码方式，这样参数会被正确添加到URL的查询字符串中，而不是作为请求体发送。
            //                return .requestParameters(parameters: params, encoding: URLEncoding.default)
            //            }
            //            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
        }
    }
    
    // 公共头部信息
    var headers: [String: String]? {
        var headers: [String: String] = [:]
        headers["token"] = UserProfile.token
        headers["client"] = "app"
        headers["Content-type"] = "application/json;charset=utf-8"
        switch self {
        case .pictureOCR:
            headers["Content-type"] = "multipart/form-data"
            
        default: break
        }
        
        headers["requestStartTime"] = String(CFAbsoluteTimeGetCurrent())
        return headers
    }
}
